package cn.jtool.dig.client.comm.tunnel.protocol;

import cn.jtool.dig.client.comm.VirtualManager;
import cn.jtool.dig.client.comm.virtual.VirtualAttrKey;
import cn.jtool.dig.client.comm.virtual.VirtualChannelInitializer;
import cn.jtool.dig.common.model.Commands;
import cn.jtool.dig.common.model.Packet;
import cn.jtool.dig.common.model.PacketBody;
import cn.jtool.dig.common.model.PacketHeader;
import cn.jtool.dig.common.netty.ProtocolProcess;
import cn.jtool.dig.common.netty.SNGenerator;
import cn.jtool.dig.common.netty.TcpClient;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class P_13_CreateSession implements ProtocolProcess {

    @Resource
    private VirtualChannelInitializer virtualChannelInitializer;

    @Override
    public int protocolId() {
        return Commands.CREATE_SESSION.getCode();
    }

    @Override
    public Packet process(ChannelHandlerContext ctx, Packet packet) {
        PacketHeader header = packet.getHeader();
        PacketBody body = packet.getBody();

        int ipLength = body.readByte();
        String ip = body.readGbkString(ipLength);
        int port = body.readWord();

        PacketHeader outheader = new PacketHeader();
        outheader.setCommand(Commands.COMMON_RESPONSE.getCode());
        outheader.setSn(SNGenerator.gen());
        outheader.setDigId(0x00);
        outheader.setChannelId(header.getChannelId());
        PacketBody outbody = new PacketBody();
        outbody.writeByte(this.protocolId());
        outbody.writeWord(header.getSn());

        TcpClient tcpClient = new TcpClient(header.getChannelId(), ip, port, this.virtualChannelInitializer);
        try {
            tcpClient.start();
            tcpClient.getChannel().attr(VirtualAttrKey.SESSION_ID).set(header.getChannelId());
            VirtualManager.addClient(tcpClient);
            outbody.writeByte(0x00);
        }catch (Exception e){
            outbody.writeByte(0x01);
            log.info("链路创建失败, {}:{}", ip, port);
        }
        ctx.channel().writeAndFlush(
                Packet.builder().header(outheader).body(outbody).build()
        );
        return null;
    }
}
